<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notepad</title>
    <style>
        .contact .list .item .content {
            width: 50% !important;
        }
    </style>

    <!-- mui -->
    <link rel="stylesheet" href="./assets/plugins/mui/css/mui.min.css">

    <!-- bootstrap -->
    <link rel="stylesheet" href="./assets/css/bootstrap.min.css" />

    <!-- animate.css -->
    <link rel="stylesheet" href="./assets/css/animate.min.css" />

    <!-- 下拉刷新插件 -->
    <link rel="stylesheet" href="./assets/plugins/mescroll/mescroll.min.css">

    <!-- 重置样式 -->
    <link rel="stylesheet/less" href="./assets/css/reset.less" />

    <!-- 公共样式 -->
    <link rel="stylesheet/less" href="./assets/css/common.less" />

    <!-- 页面独立的 -->
    <link rel="stylesheet/less" href="./assets/css/index.less" />
</head>

<body>
    <!-- 搜索 -->
    <div class="search">
        <div class="box">
            <div class="icon">
                <span class="glyphicon glyphicon-search"></span>
            </div>

            <input class="input" placeholder="请输入名字" />

            <button class="btn" id="search" size="mini" type="default">搜索</button>
        </div>
    </div>

    <!-- 分类 -->
    <div class="type wow fadeInUp mescroll-touch">
        <div class="list"></div>
    </div>

    <!-- 列表 -->
    <div id="contact" class="mescroll contact wow fadeInUp" data-wow-delay="100ms">
        <div class="list"></div>
    </div>

    <!-- 底部 -->
    <div class="tabbar">
        <div class="box">
            <a href="index.html" class="item">
                <span class="icon glyphicon glyphicon-home"></span>
                <span class="name">首页</span>
            </a>
            <a href="ContactAdd.html" class="item">
                <span class="icon glyphicon glyphicon-list-alt"></span>
                <span class="name">新建</span>
            </a>
            <a href="UserIndex.html" class="item">
                <span class="icon glyphicon glyphicon-user"></span>
                <span class="name">我的</span>
            </a>
        </div>
    </div>
</body>

</html>
<!-- 解析less的文件 -->
<script src="./assets/js/less.min.js"></script>

<!-- jquery  -->
<script src="./assets/js/jquery.min.js"></script>

<!-- mui -->
<script src="./assets/plugins/mui/js/mui.min.js"></script>

<!-- bootstrap -->
<script src="./assets/js/bootstrap.min.js"></script>

<!-- wow.js -->
<script src="./assets/js/wow.min.js"></script>

<!-- 下拉刷新插件 -->
<script src="./assets/plugins/mescroll/mescroll.min.js"></script>

<!-- axios -->
<script src="./assets/plugins/axios/axios.min.js"></script>

<!-- request -->
<script src="./assets/plugins/axios/request.js"></script>

<!-- cookie -->
<script src="./assets/plugins/cookie.js"></script>

<!-- helper -->
<script src="./assets/plugins/helper.js"></script>

<!-- lodash -->
<script src="./assets/plugins/lodash/lodash.min.js"></script>

<script>
    //实例化wow.js
    new WOW().init()

    // 检查是否已经登录
    checkLogin()

    let business = cookie.get('business') ? JSON.parse(cookie.get('business')) : {}

    // 实例化插件
    let meScroll = new MeScroll('contact', {
        // 下拉刷新
        down: {
            auto: false, // 是否在初始化完毕之后自动执行下拉回调callback; 默认true
            callback: downCallback, // 下拉刷新的回调,别写成downCallback(),多了括号就自动执行方法了
        },
        // 上拉加载
        up: {
            auto: true, // 是否在初始化时一上拉加载的方式自动加载第一页数据; 默认false
            isBounce: false, // 此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
            callback: UpCallback, // 上拉回调,此处可简写; 相当于 callback: function (page) { upCallback(page); }
            toTop: {
                //配置回到顶部按钮
                duration: 600,
                src: './assets/plugins/mescroll/mescroll-totop.png', // 默认滚动到1000px显示,可配置offset修改
                offset: 100,
                supportTap: true, // 快速响应
            },
        },
    })

    // 定义变量
    let typeid = 0,
        search = ''// 搜索的关键字

    // 下拉刷新回调函数
    async function downCallback() {
        // 自动当前页重置为第一页再触发上拉加载回调函数
        meScroll.resetUpScroll()

        // 清空列表
        $('#contact .list').empty()
    }

    // 上拉加载回调函数
    async function UpCallback(page) {
        let params = {
            page: page.num,
            limit: page.size,
            typeid,
            search,
            businessid: business.id
        }
        // console.log(page)

        let result = await POST({
            url: '/card/card/index',
            params
        })

        // console.log(result)

        if (result.code === 1) {
            // 获取数据
            let count = result.data.count ?? 0;
            let list = result.data.list ?? [];

            // 自动判断是否需要隐藏下拉刷新以及上拉加载
            meScroll.endBySize(list.length, count) // 分页功能--性能优化

            // 封装列表结构
            FetchList(list)
        } else {
            meScroll.endBySize(0, 0)
            mui.toast(result.msg)
        }
    }


    function FetchList(list = []) {
        if (list.length > 0) {
            let temp = ''

            list.forEach(item => {
                temp = `
                    <div class="item">
                        <div class="content">
                            <h3 class="title">
                                <a href="ContactAdd.html?id=${item.id}">${item.nickname}</a>
                            </h3>

                            <div class="info">
                                <div class="icon">
                                    <image src="./assets/images/info.png"></image>
                                </div>
                                <div class="desc">
                                    ${item.remark}
                                </div>
                            </div>
                        </div>
                        
                        <a href="tel:${item.mobile}">
                            <div class="call icon">
                                <image src="./assets/images/call.png"></image>
                            </div>
                        </a>

                        <button type="button" class="mui-btn mui-btn-success edit" data-id="${item.id}">编辑</button>
                        <button type="button" class="mui-btn mui-btn-danger del" data-id="${item.id}" data-nickname="${item.nickname}">删除</button>
                    </div>
                `

                $('#contact .list').append(temp)
            })
        }
    };

    // 获取分类数据
    (async () => {
        let result = await POST({
            url: '/card/card/type'
        })

        if (result.code === 1) {
            let TypeList = result.data ?? []

            TypeList.unshift({
                id: 0,
                name: '全部'
            })

            let temp = ''

            TypeList.forEach(item => {
                temp += `<div class="item ${item.id == 0 ? 'active' : ''}" data-typeid="${item.id}">${item.name}</div>`
            })

            $('.type .list').html(temp)
        }
    })();

    // 删除事件
    // console.log($('.del'))
    $('.contact .list').on('click', '.del', function () {
        // 确认框
        mui.confirm(
            `是否确认删除${this.dataset.nickname}名片`,
            '删除通讯录',
            // ['确认', '取消'],
            async res => {
                console.log(res)
                if (res.index === 1) {
                    // 获取参数
                    let params = {
                        businessid: business.id,
                        cardid: this.dataset.id
                    }
                    // 上传数据库
                    let res = await POST({
                        url: 'card/card/del',
                        params
                    })
                    // console.log(res)
                    // mui.toast(res.msg)
                    if (res.code === 1) {
                        mui.toast(res.msg)
                        // setTimeout(() => {
                        //     location.reload()
                        // }, 1000)
                        $(this).parent('.item').remove()// 直接删除元素，不用刷新页面
                    } else {
                        mui.toast(res.msg)
                    }
                } else {
                    return
                }
            }
        )
    })

    // 点击编辑跳转
    $('.contact .list').on('click', '.edit', function () {
        // 跳转页面--给地址栏传送一个被点击的id
        location.href = `ContactAdd.html?id=${this.dataset.id}`
    })

    // 点击分类切换
    $('.type .list').on('click', '.item', function () {
        // console.log(e.target.dataset.typeid)
        // console.log(e.target.innerText)
        typeid = $(this).data('typeid')
        downCallback()
        // tab栏切换--排他思想
        // JS实现
        /*
        document.querySelector('.type .list .item.active').classList.remove('active')
        this.classList.add('active')
        */
        // JQ实现
        $(this).addClass("active").siblings().removeClass("active")

    })

    // 搜索
    function inputSearch() {
        search = $.trim($('.input').val())
        downCallback()
    }
    // 防抖————防止用户频繁点击：只执行最后一次点击
    $('#search').on('click', _.debounce(inputSearch, 500))
    // 键盘点击回车
    document.querySelector('.input').addEventListener('keyup', e => {
        // console.log(e.key)
        if (e.key === 'Enter') {
            inputSearch()
        }
    })

</script>